# -*-coding:utf-8 -*-
import struct

import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
from service.proto_service import rev_msg, create_pro_from_pro

conn_dict = {}


class IndexPageHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')


class WebSocketHandler(tornado.websocket.WebSocketHandler):

    def check_origin(self, origin):
        return True

    def open(self):
        now_user_id = self.get_cookie("user_id")
        if now_user_id:
            conn_list = conn_dict.get(now_user_id)
            if conn_list:
                conn_list.append(self.ws_connection)
            else:
                conn_dict[now_user_id] = [self.ws_connection]

    def on_message(self, message):
        # 请求id
        from_user_id = self.get_cookie("user_id")
        to_user_id = rev_msg(message)

        # 重建消息 根据前端接收的消息
        re_msg = create_pro_from_pro(message, from_user_id)

        # 返回消息
        if to_user_id and conn_dict.get(str(to_user_id)):
            conn_list = conn_dict.get(str(to_user_id))
            for conn in conn_list:
                conn.write_message(re_msg)
        else:
            for user, conn_list in conn_dict.iteritems():
                for conn in conn_list:
                    conn.write_message(re_msg)

    def on_close(self):
        pass


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/', IndexPageHandler),
            (r'/ws', WebSocketHandler),
            (r'/login', LoginHandler)
        ]

        settings = {"template_path": "./template", "static_path": "./static"}
        tornado.web.Application.__init__(self, handlers, **settings)


class LoginHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('login.html')

    def post(self):
        user_id = self.get_argument("user_id")
        self.set_cookie("user_id", user_id)
        self.redirect("http://localhost:8222")


if __name__ == '__main__':
    ws_app = Application()
    server = tornado.httpserver.HTTPServer(ws_app)
    server.listen(8222)
    tornado.ioloop.IOLoop.instance().start()
